package com.zhongyu.config;

import com.zhongyu.pojo.User;
import com.zhongyu.service.PermissionService;
import com.zhongyu.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;
/*@Component*/
public class SmbmsRealm extends AuthorizingRealm {

    /*@Resource*/
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private PermissionService permissionService;

    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }
    /**
     * 提供授权信息 对主表识进行授权判定
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       User user= (User) principalCollection.getPrimaryPrincipal();
      List<String> permCodes= permissionService.searchPermCodes(user.getUserRole());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permCodes);

        return info;
    }
    /**
     * 认证
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
   String userCode= (String) token.getPrincipal();//主标识
        User user=userService.searchByUserCode(userCode);
        if (user==null){
            return  null;
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),super.getName());
        return info;
    }
}
